<template>
  <div style="height: 100%" class="workspace">
    <el-container ref="listWarp" style="height: 100%; background-color: #fff">
      <el-header class="toolbar-wap" style="height: 45px">
        <el-row :gutter="20" style="height: 100%; display: flex; align-items: center">
          <el-col :span="5">
            <el-date-picker size="small" v-model="dateData" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" @change="changeDate" style="width: 100%"></el-date-picker>
          </el-col>
          <el-col :span="3">
            <div class="colTitle">学院名称:</div>
            <el-select size="small" v-model="manageCollegeId" clearable style="width: 140px" placeholder="请选择学院名称" @change="setManageCollegeId">
              <el-option v-for="item in manageCollegeList" :key="item.collegeId" :label="item.collegeName" :value="item.collegeId"></el-option>
            </el-select>
          </el-col>
          <el-col :span="3">
            <div class="colTitle">班级名称:</div>
            <el-select size="small" v-model="classId" clearable style="width: 140px" placeholder="请选择班级名称" @change="setClassId">
              <el-option v-for="item in classList" :key="item.classId" :label="item.className" :value="item.classId"></el-option>
            </el-select>
          </el-col>
          <el-col :span="3">
            <div class="colTitle">楼宇名称:</div>
            <el-select size="small" v-model="manageBuildingId" clearable style="width: 140px" filterable placeholder="请选择楼宇名称" @change="setManageBuilding">
              <el-option v-for="item in manageBuildingList" :key="item.buildingId" :label="item.buildingName" :value="item.buildingId"></el-option>
            </el-select>
          </el-col>
          <el-col :span="3">
            <div class="colTitle">楼层:</div>
            <el-select size="small" v-model="floorId" clearable style="width: 165px" placeholder="请选择楼层名称" @change="setFloorId">
              <el-option v-for="item in floorList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-col>
          <el-col :span="5">
            <div class="colTitle">学号/姓名搜索:</div>
            <el-input size="small" placeholder="请输入学号/姓名" v-model="searchValue" clearable style="width: 180px" @change="search"></el-input>
          </el-col>
          <el-col :span="2" style="display: flex;justify-content: end;align-items: center;">
            <!--工具条按钮-->
            <ToolButton :disabled="button.disabled" :icon="button.icon" :key="button.text" :left-line="button.leftLine" :right-line="button.rightLine" :text="button.text" :title="button.title" @buttonClick="toolButtonClick" v-for="button in toolButton" style="margin-top:0;margin-right: 10px;" />
          </el-col>
        </el-row>
      </el-header>
      <el-main style="height: 100%" class="page-main">
        <div class="content" style="height: calc(100% - 60px)">
          <el-table :data="tableData" height="100%" style="width: 100%" @row-dblclick="evtTableRowdblclick" border v-loading="loadIng" :default-sort="{ prop: 'passTime', order: 'descending' }" @sort-change="changeTableSort">
            <el-table-column type="index" width="50"></el-table-column>
            <el-table-column prop="account" label="学号" width="180"></el-table-column>
            <el-table-column prop="name" label="姓名" width="180"></el-table-column>
            <el-table-column prop="collegeName" label="学院"></el-table-column>
            <el-table-column prop="className" label="班级"></el-table-column>
            <el-table-column prop="buildingName" label="楼宇" width="200px"></el-table-column>
            <el-table-column prop="roomName" label="房间" width="100px" sortable></el-table-column>
            <el-table-column prop="passTime" label="通过时间" width="180px" align="center" sortable></el-table-column>
            <el-table-column prop="createTime" label="记录时间" width="180px" align="center" sortable></el-table-column>
            <el-table-column prop="passInOut" label="进出" width="80px" align="center"></el-table-column>
            <el-table-column label="预警处理" align="center" width="80px">
              <template slot-scope="scope">
                <span style="color: red; cursor: pointer" @click="warnHandle(scope.row)">处理</span>
              </template>
            </el-table-column>
          </el-table>
          <el-footer style="height: 45px; background-color: #fff" class="page-footer">
            <el-pagination style="padding-top: 10px" background layout="prev, pager, next,jumper,total,sizes" @size-change="evtPageSizeChange" @current-change="evtPageCurrentChange" :current-page.sync="currentPage" :page-sizes="[20, 50, 100, 500]" :total="totalRows"></el-pagination>
          </el-footer>
        </div>
      </el-main>
    </el-container>
    <el-dialog title="预警处理" :visible.sync="FormVisible" width="500px" lock-scroll v-loading="diaLoading" :destroy-on-close="true" :append-to-body="true" :close-on-click-modal="false" @close="onClose">
      <div class="win-warp" style="height: 300px">
        <el-row :gutter="12">
          <el-form ref="elForm" :model="formData" :rules="rules" size="small" label-width="80px">
            <el-col :span="24">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="formData.name" placeholder="请输入姓名" maxlength="200" :style="{ width: '100%' }" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="预警处理" prop="deleteReason">
                <el-select v-model="formData.deleteReason" placeholder="请选择预警处理方式" filterable :style="{ width: '100%' }">
                  <el-option v-for="(item, index) in warnHandleList" :key="index" :label="item.name" :value="item.name"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="具体原因" prop="remark">
                <el-input v-model="formData.remark" type="textarea" placeholder="请输入具体原因" maxlength="200" :autosize="{ minRows: 4, maxRows: 4 }" :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </div>
      <div class="dialog-footer">
        <el-button @click="FormVisible = false">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
    <!--导出-->
    <export-excel ref="exportExcel" :sheet-name="sheetName" :file-name="exportFileName"  extend="export" :columns="columns" :rows="totalRows" :query="searchObj" :export-api="exportApi" :isPerSon="false"/>
  </div>
</template>
<script>
import { apiLateRecord } from "@/api/basicData/lateRecord";
import ToolButton from "@/itsoftUI/components/toolbar/toolbutton";
import exportExcel from "@/itsoftUI/components/exportExcel/recordExportExcel";
import { getPremission } from "@/itsoftUI/auth/permission";

export default {
  components: {ToolButton,exportExcel},
  data() {
    return {
      loading: false,
      toolButton: [{
          text: "导出",
          auth: "070402",
          icon: "daochu",
      }],
      exportFileName: "未归预警",
      sheetName: "未归预警",
      exportApi: apiLateRecord.getNotInRecordList,
      searchObj:{},
      columns: [{
              prop: "account",
              label: "学号",
          },{
              prop: "name",
              label: "姓名",
          },{
              prop: "collegeName",
              label: "学院",
          },{
              prop: "className",
              label: "班级",
          },{
              prop: "buildingName",
              label: "楼宇",
          },{
              prop: "roomName",
              label: "房间",
          },{
              prop: "passTime",
              label: "通过时间",
          },{
              prop: "createTime",
              label: "记录时间",
          },{
              prop: "passInOut",
              label: "进出",
          },
      ],
      FormVisible: false,
      diaLoading: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      dateData: [],
      searchValue: "",
      manageCollegeId: "",
      manageBuildingId: "",
      tableData: [],
      manageBuildingList: [],
      manageCollegeList: [],
      loadIng: false,
      currentPage: 1,
      totalRows: 0,
      pageSize: 20,
      classList: [],
      floorList: [],
      classId: "",
      floorId: "",
      formData: {
        name: "",
        deleteReason: "",
        remark: "",
      },
      currentRow: null,
      warnHandleList: null,
      deleteReason: "",
      remark: "",
      rules: {
        deleteReason: [
          {
            required: true,
            message: "请选择预警方式",
            trigger: "blur",
          },
        ],
      },
      toolButtons: [{ text: "处理", auth: "070401" }],
      order: "passTime desc",
    };
  },
  methods: {
    toolButtonClick(val){
      switch (val) {
        case "导出":
          this.$refs.exportExcel.exportOpen();
        break;
      }
    }, 
    changeDate() {
      this.getNotInRecordList( this.dateData[0], this.dateData[1], this.order);
    },
    search() {
      this.getNotInRecordList( this.dateData[0], this.dateData[1], this.order);
    },
    // 预警处理列表
    getWarnReasonList() {
      let search = [
        {
          andOr: "and",
          searchField: "dictionaryId",
          operator: "=",
          searchValue: "yjclyy",
        },
      ];
      apiLateRecord.getWarnReasonList(JSON.stringify(search)).then((res) => {
        if (res.errorCode === 0) {
          this.warnHandleList = res.data;
        }
      });
    },
    // 双击行
    evtTableRowdblclick(currentRow) {
      this.warnHandle(currentRow);
    },
    // 预警处理弹窗
    warnHandle(currentRow) {
      let edit = this.toolButtons.filter((item) => item.auth === "070401");
      if (edit && edit.length > 0 && edit[0].disabled) return false;

      (this.formData = {
        name: currentRow.name,
        deleteReason: "",
        remark: "",
      }),
        (this.currentRow = currentRow);
      this.FormVisible = true;
    },
    handelConfirm() {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          this.diaLoading = true;
          apiLateRecord.delNotInRecord(this.currentRow.id).then((res) => {
            if (res.errorCode === 0) {
              this.currentRow.deleteReason = this.formData.deleteReason;
              this.currentRow.remark = this.formData.remark;
              this.currentRow.id = "";
              apiLateRecord
                .SaveWarnHandle(JSON.stringify(this.currentRow))
                .then((res) => {
                  if (res.errorCode === 0) {
                    this.$message.success("保存成功");
                    this.onClose();
                    this.getNotInRecordList( this.dateData[0], this.dateData[1], this.order);
                  }
                });
            }
          });
        }
      });
    },
    onClose() {
      this.diaLoading = false;
      this.$refs["elForm"].resetFields();
      this.FormVisible = false;
    },
    getNotInRecordList(startDate, endDate, sortStr) {
      this.loadIng = true;
      let search = [];
      search.push({
        andOr: "and",
        searchField: "passTime",
        operator: ">=",
        searchValue: startDate,
      });
      search.push({
        andOr: "and",
        searchField: "passTime",
        operator: "<=",
        searchValue: endDate,
      });
      if (/^\d+(\.\d+)?$/.test(this.searchValue) && this.searchValue) {
        search.push({
          andOr: "and",
          searchField: "account",
          operator: "=",
          searchValue: this.searchValue,
        });
      } else if (this.searchValue) {
        search.push({
          andOr: "in",
          searchField: "name",
          operator: "=",
          searchValue: this.searchValue,
        });
      }
      if (this.manageBuildingId) {
        search.push({
          andOr: "and",
          searchField: "buildingId",
          operator: "=",
          searchValue: this.manageBuildingId,
        });
      }
      if (this.manageCollegeId) {
        search.push({
          andOr: "and",
          searchField: "collegeId",
          operator: "=",
          searchValue: this.manageCollegeId,
        });
      }
      if (this.classId) {
        search.push({
          andOr: "and",
          searchField: "classId",
          operator: "=",
          searchValue: this.classId,
        });
      }
      if (this.floorId) {
        search.push({
          andOr: "and",
          searchField: "floor",
          operator: "=",
          searchValue: this.floorId,
        });
      }
      let page = { pageIndex: this.currentPage, pageSize: this.pageSize };
      this.searchObj.search = search;
      this.searchObj.order = sortStr;
      this.searchObj.tag = "lateNightRecord";
      apiLateRecord.getNotInRecordList(JSON.stringify(search),JSON.stringify(page),sortStr).then((res) => {
          if (res.errorCode === 0) {
            this.tableData = res.data.rows;
            this.totalRows = res.data.total;
            this.loadIng = false;
          }
        });
    },
    changeTableSort(column) {
      if (column.order == "ascending") {
        this.order = column.prop + " asc";
        this.getNotInRecordList(
          this.dateData[0],
          this.dateData[1],
          column.prop + " asc"
        );
      } else if (column.order == "descending") {
        this.order = column.prop + " desc";
        this.getNotInRecordList(
          this.dateData[0],
          this.dateData[1],
          column.prop + " desc"
        );
      }
    },
    evtPageSizeChange(val) {
      //每页数量
      this.pageSize = val;
      this.getNotInRecordList( this.dateData[0], this.dateData[1], this.order);
    },
    evtPageCurrentChange(val) {
      //分页
      this.currentPage = val;
      this.getNotInRecordList( this.dateData[0], this.dateData[1], this.order);
    },
    getAuthList(collegeId) {
      apiLateRecord.getAuthList(collegeId).then((res) => {
        if (res.errorCode === 0) {
          // 楼宇
          this.manageBuildingList = res.data.buildList;
          // 学院
          this.manageCollegeList = res.data.collegeList;
          // 班级
          this.classList = res.data.classList;
        }
      });
    },
    setManageBuilding() {
      //生成楼层
      this.manageBuildingList.forEach((item) => {
        if (item.buildingId == this.manageBuildingId) {
          for (let i = item.downFloor; i <= item.upFloor; i++) {
            this.floorList.push({ name: i, id: i });
          }
        }
      });

      this.getNotInRecordList( this.dateData[0], this.dateData[1], this.order);
    },
    setManageCollegeId() {
      this.getAuthList(this.manageCollegeId);
      this.getNotInRecordList( this.dateData[0], this.dateData[1], this.order);
    },
    setClassId() {
      this.getNotInRecordList( this.dateData[0], this.dateData[1], this.order);
    },
    setFloorId() {
      this.getNotInRecordList( this.dateData[0], this.dateData[1], this.order);
    },
  },
  created() {
    getPremission(this.toolButton);
    //昨天的时间
    let time = new Date().getTime() - 24 * 60 * 60 * 1000;
    let yesterday = new Date(time);
    let beforeDay =
      yesterday.getFullYear() +
      "-" +
      (yesterday.getMonth() > 9
        ? yesterday.getMonth() + 1
        : "0" + (yesterday.getMonth() + 1)) +
      "-" +
      (yesterday.getDate() > 9
        ? yesterday.getDate()
        : "0" + yesterday.getDate());
    //今天的时间
    let myDate = new Date(); //获取当前年份(2位)
    let year = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
    let month = myDate.getMonth(); //获取当前月份(0-11,0代表1月)
    let day = myDate.getDate(); //获取当前日(1-31)
    let defaultDate =
      year +
      "-" +
      (month + 1 > 9 ? month + 1 : "0" + (month + 1)) +
      "-" +
      (day > 9 ? day : "0" + day);
    this.dateData[0] = "" + beforeDay;
    // this.dateData[1] = "" + defaultDate; // 截止到今天
    this.dateData[1] = "" + beforeDay;  // 截止到昨天
    this.getNotInRecordList(
      this.dateData[0],
      this.dateData[1],
      this.order
    );
    this.getAuthList();
    this.getWarnReasonList();
    //功能权限
    getPremission(this.toolButtons);
  },
};
</script>
<style scoped>
.colTitle {
  display: inline-block;
  margin-right: 10px;
  line-height: 34px;
}
</style>